package com.trans.handler;

import com.trans.anno.Desensitise;
import com.trans.anno.Translator;
import com.trans.auxiliary.HandleFullRecord;
import com.trans.auxiliary.HandleRecord;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author xwduo
 * @Description 脱敏处理
 * @Date 2023-06-28 10:14
 */
public class InfoDesensitise implements TranslateHandle<String,Object> {

    private static final String FULL_DESENSITISE = "****";

    @Override
    public Object doHandle(HandleRecord record, Map<String, Object> cacheMap) {
        Translator translator = record.translator;
        //覆盖原值
        String fieldName = record.fieldName;
        record.setRename(fieldName);
        Desensitise annotation = record.getAnnotation(Desensitise.class);
        if(null != annotation){
            Object curItemVal = record.getVal();
            if(Objects.nonNull(curItemVal)){
                String info = String.valueOf(curItemVal);
                int prefix = annotation.prefix();
                int suffix = annotation.suffix();
                int middle = annotation.middle();
                return desensitization(annotation.isAll(),prefix,middle,suffix,info);
            }
            return curItemVal;
        }
        return null;
    }



    private static String desensitization(boolean isAll,int prefix,int middle,int suffix,String val){
        String info = String.valueOf(val);
        int infoLength = info.length();
        if(isAll || prefix>infoLength || suffix>infoLength || middle>infoLength || (prefix+suffix+middle)>=infoLength){
            return FULL_DESENSITISE;
        }else {
            StringBuilder builder = new StringBuilder();
            String suffixStr = "";
            if(prefix>0 ){
                builder.append(FULL_DESENSITISE);
                info = info.substring(prefix);
                infoLength = info.length();
            }
            if(suffix>0 ){
                suffixStr = FULL_DESENSITISE;
                info = info.substring(0,infoLength-suffix);
                infoLength = info.length();
            }
            if(middle>0 ){
                int showLength = (infoLength - middle) / 2;
                info = info.substring(0, showLength).concat(FULL_DESENSITISE).concat(info.substring(showLength + middle, infoLength));
            }
            return builder.append(info).append(suffixStr).toString();
        }
    }



    @Override
    public Map<String, Object> cache(List<HandleFullRecord> recordList) {
        return null;
    }

    @Override
    public int order() {
        return 0;
    }


}
